#!/usr/bin/env python
#-*- coding: GB2312 -*-

import sys
from datetime import datetime

import importme
from models import model, page_parse
from utils.test_util import profile

db_reader = model.reader
db_writer = model.writer


def main():
    products = db_reader.product.where(interested=True).select()
    if not products:
        return

    products = dict([(p['id'], p) for p in products])

    pids = products.keys()

    old_price = dict.fromkeys(pids, set())

    for i in db_reader.price.where(product_id__in=pids).select():
        old_price[i['product_id']].add(i['price'])

    d = []
    for pid in pids:
        try:
            cur_price = page_parse.parse_price(pid)
        except:
            continue

        d.append((
            pid,
            datetime.now(),
            page_parse.parse_price(pid)
        ))

        if cur_price <= min( old_price[pid] ):
            #TODO
            # notify_me()
            pass

    db_writer.price.insert_many(('product_id', 'get_time', 'price'), d)


if __name__ == '__main__':
    main()
    
